<template>
  <div>
    <!-- 下拉选择框 -->
    <el-select
      :title="optionData.name"
      ref="select"
      :value="value"
      :placeholder="placeholder"
      clearable
      :disabled="disabled"
      :filterable="filterable"
      :filter-method="filterMethod"
      style="width: 100%"
      @clear="clear"
      @visible-change="visibleChange"
    >
      <!-- 下拉选项 -->
      <el-option
        ref="option"
        class="tree-select__option"
        :value="optionData.id"
        :label="optionData.name"
      >
        <!-- 树形结构 -->
        <el-tree
          style=""
          ref="tree"
          class="tree-select__tree tree-select__tree--radio"
          :node-key="nodeKey"
          :data="data"
          :props="props"
          :default-expanded-keys="[value]"
          :highlight-current="true"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        ></el-tree>
      </el-option>
    </el-select>
  </div>
</template>
 
<script>
export default {
  name: "TreeSelect",
  props: {
    // 提示文本
    placeholder: {
      type: String,
    },
    // v-model绑定的值
    value: {
      type: [String, Number],
      default: "",
    },
    // 树形的数据
    data: {
      type: Array,
      default: function () {
        return [];
      },
    },
    // 每个树节点用来作为唯一标识的属性
    nodeKey: {
      type: [String, Number],
      default: "id",
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: true,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // tree的props配置
    props: {
      type: Object,
      default: function () {
        return {
          label: "label",
          children: "children",
        };
      },
    },
  },
  data() {
    return {
      // 选中的节点数据
      optionData: {
        id: "",
        name: "",
      },
      // 标记是否进行了过滤
      filterFlag: false,
    };
  },
  watch: {
    // 监听value的变化
    value: {
      handler(val) {
        if (!this.isEmpty(this.data)) {
          this.init(val);
        }
      },
      immediate: true,
    },
    // 监听data的变化
    data: function (val) {
      if (!this.isEmpty(val)) {
        this.init(this.value);
      }
    },
  },
  created() {},
  mounted() {
    // 添加监听事件，用于处理文档body上的点击事件
    document.body.addEventListener("click", this.handleBodyClick);
  },
 
  beforeDestroy() {
    // 销毁监听事件
    document.body.removeEventListener("click", this.handleBodyClick);
  },
  methods: {
    // 判断对象是否为空
    isEmpty(val) {
      for (let key in val) {
        return false;
      }
      return true;
    },
    // 处理节点点击事件
    handleNodeClick(data) {
      const selectedValue = data[this.nodeKey];
      // 检查选中值是否真正变化
      if (selectedValue !== this.value) {
        this.optionData.name = data[this.props.label];
        this.$emit("input", selectedValue);
        this.$emit("change", selectedValue);
      }
      this.$refs.select.visible = false;
    },
    // 初始化选中值
    init(val) {
      val = val === "" ? null : val;
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(val);
        if (val === null) {
          return;
        }
        const node = this.$refs.tree.getNode(val);
        this.optionData.id = val;
        this.optionData.name = node.label;
      });
      this.flag = true;
    },
    // 下拉框显示状态变化的回调函数
    visibleChange(e) {
      if (e) {
        const tree = this.$refs.tree;
        this.filterFlag && tree.filter("");
        this.filterFlag = false;
        let selectDom = tree.$el.querySelector(".is-current");
        setTimeout(() => {
          this.$refs.select.scrollToOption({ $el: selectDom });
        }, 0);
      }
    },
    // 清空选中值的回调函数
    clear() {
      if (this.value) {
        this.$emit("input", "");
        this.$emit("change", "");
      }
    },
    // 下拉框搜索的回调函数
    filterMethod(val) {
      this.filterFlag = true;
      this.$refs.tree.filter(val);
    },
    // 树节点过滤的方法
    filterNode(value, data) {
      if (!value) return true;
      const label = this.props.label || "name";
      return data[label].indexOf(value) !== -1;
    },
    // 处理文档body上的点击事件
    handleBodyClick(event) {
      // 检查点击是否发生在下拉框外部
      if (this.$refs.select && !this.$refs.select.$el.contains(event.target)) {
        // 关闭下拉框
        this.$refs.select.visible = false;
      }
    },
  },
};
</script>
 
<style lang="scss">
/* 下拉选项样式 */
.tree-select__option {
  &.el-select-dropdown__item {
    height: auto;
    line-height: 1;
    padding: 0;
    background-color: #fff;
  }
}
 
/* 树形结构样式 */
.tree-select__tree {
  color: #333333;
  padding: 4px 20px;
  font-weight: 400;
  &.tree-select__tree--radio {
    /* 选中节点样式 */
    .el-tree-node.is-current > .el-tree-node__content {
      font-weight: 700;
    }
  }
}
</style>